﻿/*
 声音进度条录制时需要；
 
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web;
using Dingding.Helper;

namespace Common
{ /// <summary>
  /// 。
  /// </summary>
    public static class ClassL2Ai
    {
      
        public static string get_imageUrl(string ip)
        {

            string ps_name = "get_imageUrl";
            string host = "http://192.168.121.248:82/hik_robot/camera/get_image";
           



            string imageUrl = "-1";//表示异常；
            HttpWebRequest req = null;
            HttpWebResponse resp = null;
            Stream stream = null;

            string msg = "";

            try
            {



                string result = "";
                req = (HttpWebRequest)WebRequest.Create(host);
                req.Method = "POST";
                string boundary = String.Format("----------{0:N}", Guid.NewGuid());


                req.ContentType = "multipart/form-data; boundary=" + boundary;
                req.Headers.Add("sinzetech-auth", "");
                req.CookieContainer = new CookieContainer();



                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("device", ip);//10.233.121.18
                                             //parameters.Add("PeoSex", addVisitorRequestDto.PeoSex);





                byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");


                msg = "Stream requestStream = req.GetRequestStream()---------begin";


                using (Stream requestStream = req.GetRequestStream())
                {
                    foreach (KeyValuePair<string, object> pair in parameters)
                    {
                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                        string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
                        requestStream.Write(bytes, 0, bytes.Length);
                    }

                    byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                    requestStream.Write(trailer, 0, trailer.Length);
                    requestStream.Close();
                }

                msg = "Stream requestStream = req.GetRequestStream()---------end";


                resp = (HttpWebResponse)req.GetResponse();

                msg = "(HttpWebResponse)req.GetResponse()---------end";


                stream = resp.GetResponseStream();



                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }

                msg = "PostGetUserInfo--result:\n" + result;


                JObject jObject = JObject.Parse(result);

                if (jObject["code"].ToString() != "200")
                {
                    ClassMyFile.WriteLog("摄像头抓拍异常:\n" + result, ps_name);
                }
                else
                {
                    imageUrl = jObject["data"]["ossUrl"].ToString();
                }

            }
            catch (Exception ex)
            {
                ClassMyFile.WriteLog("[" + msg + "],出现Exception ex:\n" + ex.ToString(), ps_name);
            }
            finally
            {
                if (req != null)
                    req.Abort();

                if (resp != null)
                    resp.Close();

                if (stream != null)
                    stream.Close();

            }

            return imageUrl;



        }


        public static string get_imageOcr(string imageUrl, string type)
        {
            string ps_name = "get_imageOcr";


            //默认C型钩
            string host = "http://192.168.121.248:81/code/track_hanger_number";
            string range = "";
            string rotate = "";

            string deleteProbability = "0";//: 低于这个概率删除 如果保留所有传入0  钩默认0.7 卷：0
            string minNumberCount = "0";  //最低保留多少个 钩默认2 ;卷：3;删除低概率，保留至


 




            if (type == "A") //钢坯
            {
                host = "http://192.168.121.248:81/code/track_number";
            }
            else if (type == "B") //卷芯架
            {
                host = "http://192.168.121.248:81/code/track_shelf_number";
            }
            else if (type == "B1") //卷芯架，旋转3度
            {
                host = "http://192.168.121.248:81/code/track_shelf_number";
               

                if (imageUrl.Contains("IP_10.233.121.6"))
                {
                    rotate = "-98";
                    //有时比框还有好呢。
                }
                else if (imageUrl.Contains("IP_10.233.121.8"))
                {
                    rotate = "95";
                }
                else 
                {
                    rotate = "3";
                }


            }
            else if (type == "BX") //卷芯架
            {
                host = "http://192.168.121.248:81/code/track_shelf_number";


                //目前是写死，后面需要优化调整成动态的；
                if (imageUrl.Contains("IP_10.233.121.3"))
                {
                   // range = "[[198,195],[386,198],[382,393],[211,388]]";
                }
                else if (imageUrl.Contains("IP_10.233.121.4"))
                {
                    //range = "[[24,169],[430,138],[425,422],[24,500]]";
                }
                else if (imageUrl.Contains("IP_10.233.121.5"))
                {
                   // range = "[[211,35],[661,100],[623,837],[143,749]]";
                }
                else if (imageUrl.Contains("IP_10.233.121.6"))
                {
                    //range = "[[354,329],[899,230],[942,825],[499,950]]";
                }
                else if (imageUrl.Contains("IP_10.233.121.8"))
                {
                    //range = "[[56,99],[196,121],[178,320],[43,300]]";
                    rotate = "95";
                }

            }
            else if (type == "C1") //C型钩，旋转3度
            {
                host = "http://192.168.121.248:81/code/track_hanger_number";
                rotate = "-1"; 
            }
            else if (type == "C2") //C型钩，旋转3度
            {
                host = "http://192.168.121.248:81/code/track_hanger_number";
                rotate = "-2";
            }
            else if (type == "C3") //C型钩，旋转3度
            {
                host = "http://192.168.121.248:81/code/track_hanger_number";
                if (imageUrl.Contains("IP_10.233.121.16")) //默认是-3
                { 
                    rotate = "0"; 
                }
                else
                {
                    rotate = "-3";
                }
            }
            else if (type == "C11") //C型钩，旋转3度
            {
                host = "http://192.168.121.248:81/code/track_hanger_number";
                rotate = "1";
            }
            else if (type == "C12") //C型钩，旋转3度
            {
                host = "http://192.168.121.248:81/code/track_hanger_number";
                rotate = "2";
            }
            else if (type == "C13") //C型钩，旋转3度
            {
                host = "http://192.168.121.248:81/code/track_hanger_number";
                rotate = "3";
            } 


            else if (type == "C1Y") //add by wb 2024-08-12
            {
                host = "http://192.168.121.248:81/code/track_hanger_number";
                rotate = "-3";                  
                deleteProbability = "0.1"; 
                minNumberCount = "2";   
            }


            //host = host.Replace("192.168.121.248:81", "192.168.1.188:7070");




            string str_num = "-1";//表示异常；
            HttpWebRequest req = null;
            HttpWebResponse resp = null;
            Stream stream = null;

            string msg = "";

            try
            {



                string result = "";
                req = (HttpWebRequest)WebRequest.Create(host);
                req.Method = "POST";
                string boundary = String.Format("----------{0:N}", Guid.NewGuid());


                req.ContentType = "multipart/form-data; boundary=" + boundary;
                req.Headers.Add("sinzetech-auth", "");
                req.CookieContainer = new CookieContainer();



                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("imageUrl", imageUrl);


                if (type == "BX") //卷芯架
                {
                    parameters.Add("range", range);  ////  range = 识别范围(可选参数)
                    parameters.Add("rotate", rotate); ////rotate=旋转角度(可选参数)
                }
                else if (type == "B1"
                    || type == "C1" || type == "C2" || type == "C3"
                    || type == "C11" || type == "C12" || type == "C13") //卷芯架 C型钩
                { 
                    parameters.Add("rotate", rotate); ////rotate=旋转角度(可选参数)
                }


                else if (type == "C1Y") //C型钩
                {
                    parameters.Add("rotate", rotate); ////rotate=旋转角度(可选参数)

                    parameters.Add("deleteProbability", deleteProbability);
                    parameters.Add("minNumberCount", minNumberCount); 

                }




                byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");


                msg = "Stream requestStream = req.GetRequestStream()---------begin";


                using (Stream requestStream = req.GetRequestStream())
                {
                    foreach (KeyValuePair<string, object> pair in parameters)
                    {
                        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                        string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
                        requestStream.Write(bytes, 0, bytes.Length);
                    }

                    byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                    requestStream.Write(trailer, 0, trailer.Length);
                    requestStream.Close();
                }

                msg = "Stream requestStream = req.GetRequestStream()---------end";


                resp = (HttpWebResponse)req.GetResponse();

                msg = "(HttpWebResponse)req.GetResponse()---------end";


                stream = resp.GetResponseStream();



                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }

                msg = "PostGetUserInfo--result:\n" + result;





                ClassMyFile.WriteLog("图形识别结果:\n" + msg, ps_name);


                JObject jObject = JObject.Parse(result);

                if (jObject["code"].ToString() != "200")
                {
                    ClassMyFile.WriteLog("图形识别错误:\n" + result, ps_name);
                    return str_num;
                }

                if (type != "A") //不是钢坯
                {
                    str_num = jObject["data"]["number"].ToString();
                }

               //修正[担心死循环]，应放在业务程序中，本程序就是拍照的原始识别；
               //str_num = MatHangerNumber.GetHangerNumber_OK(str_num, 0);







            }
            catch (Exception ex)
            {
                ClassMyFile.WriteLog("[" + msg + "],出现Exception ex:\n" + ex.ToString(), ps_name);
            }
            finally
            {
                if (req != null)
                    req.Abort();

                if (resp != null)
                    resp.Close();

                if (stream != null)
                    stream.Close();

            }

            return str_num;



        }



        public static string get_PicOcr(string ip, string type)
        {
            string ps_name = "get_PicOcr";
            string msg = "-1";//表示异常；  17E10
            int i = 0;


            DateTime dt0 = DateTime.Now;
            DateTime dt1 = DateTime.Now;
            TimeSpan timeDifference;
            int subTime = 0;




            //1图片打开识别；-------------------------------------


            string imageUrl = ClassL2Ai.get_imageUrl(ip);

            //防止图片打开错误，共执行3次；每次间隔1.2秒；
            i = 1;
            while (imageUrl == "-1" && i < 3)
            {
                i++;
                System.Threading.Thread.Sleep(1200);
                imageUrl = ClassL2Ai.get_imageUrl(ip);
            }

            timeDifference = DateTime.Now - dt1;
            subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;


            ClassMyFile.WriteLog(string.Format("get_imageUrl,耗时{0}ms, 第[{1}]次拍照", subTime, i), ps_name);

            dt1 = DateTime.Now;


            if (imageUrl == "-1")
            {
                msg = string.Format("-1 get_imageUrl，照片抓取识别,IP{0}, imageUrl[{1}]", ip, imageUrl);
                ClassMyFile.WriteLog(msg, ps_name);
                return msg;
            }




            string str_num = ClassL2Ai.get_imageOcr(imageUrl, type);



            timeDifference = DateTime.Now - dt0;
            subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;

            ClassMyFile.WriteLog(string.Format("get_imageOcr,总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num,ip), ps_name);
            dt1 = DateTime.Now;

            if (str_num.Contains("-1"))
            {
                msg = string.Format("-1 get_imageOcr，图形识别错误,IP{0}, imageUrl[{1}]", ip, imageUrl);
                ClassMyFile.WriteLog(msg, ps_name);
                return msg;
            } 

            return str_num;
        }


        public static string get_PicOcr2(string ip, string type)
        {
            string ps_name = "get_PicOcr2";
            string msg = "-1";//表示异常；  17E10
            int i = 0;


            DateTime dt0 = DateTime.Now;
            DateTime dt1 = DateTime.Now;
            TimeSpan timeDifference;
            int subTime = 0;




            //1图片打开识别；-------------------------------------


             string imageUrl = ClassL2Ai.get_imageUrl(ip);


             // string   imageUrl = "http://192.168.11.120:9000/material-tracking/upload/ai_model/c/IMG_1725100427829.jpg";
            // IMG 1723450836287jpg
                                        
            


            //防止图片打开错误，共执行3次；每次间隔1.2秒；
            i = 1;
            while (imageUrl == "-1" && i < 3)
            {
                i++;
                System.Threading.Thread.Sleep(1200);
                imageUrl = ClassL2Ai.get_imageUrl(ip);
            }

            timeDifference = DateTime.Now - dt1;
            subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;


            ClassMyFile.WriteLog(string.Format("get_imageUrl,耗时{0}ms, 第[{1}]次拍照[{2}]", subTime, i, imageUrl), ps_name);

            dt1 = DateTime.Now;


            if (imageUrl == "-1")
            {
                msg = string.Format("-1 get_imageUrl，照片抓取识别,IP{0}, imageUrl[{1}]", ip, imageUrl);
                ClassMyFile.WriteLog(msg, ps_name);
                return msg;
            }



            int number; 
            string str_num = ClassL2Ai.get_imageOcr(imageUrl, type);
            int.TryParse(str_num, out number);




            timeDifference = DateTime.Now - dt0;
            subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
            ClassMyFile.WriteLog(string.Format("get_imageOcr_1(-1),总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num, ip), ps_name);
            dt1 = DateTime.Now;



            //若识别，默认为0的，比如字符串含义字母； 
           
            




            //针对C1，则2次识别，分别为正【-3，+3】
            if (type == "C1"
                &&  (   number < 1 || number >121  || str_num.Length ==1   )
                )
            {
                str_num = ClassL2Ai.get_imageOcr(imageUrl, "C2");
                int.TryParse(str_num, out number);

                timeDifference = DateTime.Now - dt0;
                subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                ClassMyFile.WriteLog(string.Format("get_imageOcr_1(-2),总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num, ip), ps_name);
                dt1 = DateTime.Now;
                 


                //add by wb 2024-08-12 修正，解决还是
                if (number < 1 || number > 121 || str_num.Length == 1)
                {
                    str_num = ClassL2Ai.get_imageOcr(imageUrl, "C3");
                    int.TryParse(str_num, out number);
                    timeDifference = DateTime.Now - dt0;
                    subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                    ClassMyFile.WriteLog(string.Format("get_imageOcr_1(-3),总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num, ip), ps_name);
                    dt1 = DateTime.Now;
                }


                if (number < 1 || number > 121 || str_num.Length == 1)
                {
                    str_num = ClassL2Ai.get_imageOcr(imageUrl, "C11");
                    int.TryParse(str_num, out number);

                    timeDifference = DateTime.Now - dt0;
                    subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                    ClassMyFile.WriteLog(string.Format("get_imageOcr_1(+1),总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num, ip), ps_name);
                    dt1 = DateTime.Now;
                }



                if (number < 1 || number > 121 || str_num.Length == 1)
                {
                    str_num = ClassL2Ai.get_imageOcr(imageUrl, "C12");
                    int.TryParse(str_num, out number);

                    timeDifference = DateTime.Now - dt0;
                    subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                    ClassMyFile.WriteLog(string.Format("get_imageOcr_1(+2),总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num, ip), ps_name);
                    dt1 = DateTime.Now;
                }


                if (number < 1 || number > 121 || str_num.Length == 1)
                {
                    str_num = ClassL2Ai.get_imageOcr(imageUrl, "C13");
                    int.TryParse(str_num, out number);

                    timeDifference = DateTime.Now - dt0;
                    subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                    ClassMyFile.WriteLog(string.Format("get_imageOcr_1(+3),总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num, ip), ps_name);
                    dt1 = DateTime.Now;
                }


                //add by wb 2024-08-12 修正，解决还是
                if (number < 1 || number > 121 || str_num.Length == 1)
                {
                    str_num = ClassL2Ai.get_imageOcr(imageUrl, "C1Y");
                    int.TryParse(str_num, out number);

                    timeDifference = DateTime.Now - dt0;
                    subTime = (timeDifference.Hours * 3600 * 1000) + (timeDifference.Minutes * 60 * 1000) + (timeDifference.Seconds * 1000) + timeDifference.Milliseconds;
                    ClassMyFile.WriteLog(string.Format("get_imageOcr_1(C1Y),总耗时[{0}]ms, 数字[{1}]，IP[{2}]", subTime, str_num, ip), ps_name);
                    dt1 = DateTime.Now;
                }


            }
             




            if (str_num.Contains("-1"))
            {
                msg = string.Format("-1 get_imageOcr，图形识别错误,IP{0}, imageUrl[{1}]", ip, imageUrl);
                ClassMyFile.WriteLog(msg, ps_name);
                return msg;
            }



            return str_num;
        }


    }



    public static class get_order
    {
        private static int i = 0;

        //初次调用需要
        private static DateTime dt_last = DateTime.Now.AddSeconds(-200);

        public static int get_order_num()
        {
            //
            if (dt_last.ToString("yyyyMMdd") != DateTime.Now.ToString("yyyyMMdd"))
            {
                i = 1;
            }
            else
            {
                i++;
            }

            return i;
        }

        public static DateTime get_dt_last()
        {
            return dt_last;
        }

        public static void set_dt_last()
        {
            dt_last = DateTime.Now;
        }
    }


    public static class get_order2 
    {
        private static int i = 0;

        //初次调用需要
        private static DateTime dt_last = DateTime.Now.AddSeconds(-200);

        public static int get_order_num()
        {
            //
            if (dt_last.ToString("yyyyMMdd") != DateTime.Now.ToString("yyyyMMdd"))
            {
                i = 1;
            }
            else
            {
                i++;
            }

            return i;
        }

        public static DateTime get_dt_last()
        {
            return dt_last;
        }

        public static void set_dt_last()
        {
            dt_last = DateTime.Now;
        }
    }


  
}
